package cn.le;

import cn.le.entty.ErrorVO;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice // 定义统一异常处理类
public class MyException {
    // @ExceptionHandler 用来定义函数针对的异常类型
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e)
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception",e);
        modelAndView.addObject("url",req.getRequestURI());
        modelAndView.setViewName("error");//返回的页面
        return modelAndView;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody //处理函数return内容自动转换为json格式
    public ErrorVO jsonErrorHandler(HttpServletRequest req, Exception e)
    {
        ErrorVO errorInfo = new ErrorVO();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setCode(-1);
        return errorInfo;
    }
}
